import HYRequest from './request'
import { BASE_URL, TIME_OUT, ContentTypeEnum } from './config'

import { sessionCache } from '@/utils/cache'

const hyRequest = new HYRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  headers: { 'Content-Type': ContentTypeEnum.JSON },
  interceptors: {
    requestSuccessFn: (config) => {
      // 每一个请求都自动携带token
      const userInfo = sessionCache.getCache('userInfo')

      if (config.headers && userInfo?.token) {
        config.headers.token = userInfo?.token
      }

      // 请求头类型
      if (config.headers && config.isJson) {
        config.headers['Content-Type'] = ContentTypeEnum.JSON
      } else if (config.headers && config.isFormData) {
        config.headers['Content-Type'] = ContentTypeEnum.FORM_DATA
      } else if (config.headers && config.isFormUrlEncode) {
        config.responseType = 'blob'
        config.headers['Content-Type'] = ContentTypeEnum.FORM_URLENCODED
      } else if (config.headers && config.isJsonUrlEncode) {
        config.responseType = 'blob'
        config.headers['Content-Type'] = ContentTypeEnum.JSON_URLENCODED
      }

      // 云直传请求头类型
      if (config.headers && config.xAmzAcl) {
        config.headers = {
          'Content-Type': config.fileType,
          'x-amz-acl': 'public-read'
        }
      }

      return config
    },
    requestFailureFn: (err) => {
      return err
    },
    responseSuccessFn: (res) => {
      return res.data
    },
    responseFailureFn: (err) => {
      return err
    }
  }
})

export default hyRequest
